from flask import render_template, g, redirect, request, jsonify, current_app, abort

from info.constants import QINIU_DOMIN_PREFIX, USER_COLLECTION_MAX_NEWS, OTHER_NEWS_PAGE_MAX_COUNT, \
    USER_FOLLOWED_MAX_COUNT
from info.models import Category, News, User
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from info.utils.response_code import RET
from info import db
from . import pro_blu

@pro_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        "user":user.to_dict() if user else None
    }
    return render_template('news/user.html',data=data)

@pro_blu.route('/base_info',methods=['GET','POST'])
@user_login_data
def base_info():
    user = g.user
    if request.method == 'GET':
        data = {
            "user":user.to_dict()
        }
        return render_template('news/user_base_info.html',data=data)

    # post 修改用户数据
    signature = request.json.get('signature')
    nick_name = request.json.get('nick_name')
    gender = request.json.get('gender')
    print(gender)

    if not all([nick_name,signature,gender]):
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    if gender not in ['MAN','WOMAN']:
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    user.signature = signature
    user.gender = gender
    user.nick_name = nick_name

    return jsonify(errno=RET.OK,errmsg='ok')

@pro_blu.route('/pic_info',methods=['GET','POST'])
@user_login_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        data ={
            "user":user
        }
        return render_template('news/user_pic_info.html',data=data)
    # 1、取到上传图片
    try:
        avatar = request.files.get("avatar").read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')
    # 2、上传头像
    try:
       key = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='上传头像失败')

    # 3、保存头像地址
    user.avatar_url = key

    return jsonify(errno=RET.OK,errmsg='ok',data={"avator_url":QINIU_DOMIN_PREFIX+key})

@pro_blu.route('/update_pass',methods=['GET','POST'])
@user_login_data
def update_pass():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')

    # 1、获取参数
    old_pass = request.json.get('old_password')
    new_pass = request.json.get('new_password')

    # 2、校验参数
    if not all([old_pass,new_pass]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if not user.check_password(old_pass):
        return jsonify(errno=RET.PWDERR,errmsg='原密码错误')

    # 3、保存参数
    user.password = new_pass
    return jsonify(errno=RET.OK, errmsg='OK')

@pro_blu.route('/collection')
@user_login_data
def user_collection():
    page = request.args.get('page',1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user = g.user
    news_list = []
    try:
        paginate = user.collection_news.paginate(page,USER_COLLECTION_MAX_NEWS)
        total_page = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "page":page,
        "total_page":total_page,
        "collections":news_dict_li
    }

    return render_template('news/user_collection.html',data=data)


@pro_blu.route('/news_release',methods=['GET','POST'])
@user_login_data
def news_release():
    if request.method == 'GET':
        category_list = None
        try:
            category_list = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
        category_dict_li = []
        for category in category_list:
            category_dict_li.append(category.to_dict())

        category_dict_li.pop(0)

        data = {
            "category":category_dict_li
        }
        return render_template('news/user_news_release.html',data=data)
    user = g.user
    # 1、获取参数
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    source = "个人发布"
    print(title,category_id,digest,index_image,content,source)

    if not all([title,category_id,digest,index_image,content,source]):
        return jsonify(errno=RET.PARAMERR, errmsg='有空值参数错误')

    try:
        category_id = int(category_id)
    except Exception as e:
        return jsonify(errno=RET.PARAMERR,errmsg='参数错误')

    # 取到照片 将图片上传到七牛云
    # try:
    #     index_image_data = index_image.read()
    #     key = storage(index_image_data)
    # except Exception as e:
    #     current_app.logger.error(e)
    #     return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.content = content
    news.index_image_url = QINIU_DOMIN_PREFIX
    news.source = source
    news.user_id = user.id
    news.status = 1 # 待审核

    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='数据保存失败')

    return jsonify(errno=RET.OK,errmsg='ok')


@pro_blu.route('/news_list')
@user_login_data
def news_list():
    page = request.args.get('page',1)
    print(page)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    total_page = 1

    user = g.user
    news_list = []
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(page,1)
        total_pages = paginate.pages
        news_list = paginate.items
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        "total_pages":total_pages,
        "page":page,
        "news_dict_li":news_dict_li
    }
    return render_template('news/user_news_list.html',data=data)


@pro_blu.route('/user_follow')
@user_login_data
def user_follow():
    user = g.user
    page = request.args.get('page',1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    user_followers = []
    total_pages = 1
    try:
        paginate = user.followed.paginate(page,USER_FOLLOWED_MAX_COUNT)
        user_followers = paginate.items
        total_pages = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    followers_dict_li = []
    for follower in user_followers:
        followers_dict_li.append(follower.to_dict())

    data = {
        "followers_dict_li":followers_dict_li,
        "page":page,
        "total_pages":total_pages
    }
    return render_template('news/user_follow.html',data=data)


@pro_blu.route('/other_info')
@user_login_data
def other_info():
    other_id = request.args.get('user_id')
    print(other_id)
    if not other_id:
        abort(404)

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)
    user = g.user
    is_followed = False
    if user and other:
        if other in user.followed:
            is_followed = True

    data= {
        "user":user.to_dict()if user else None,
        "other":other.to_dict(),
        "is_followed":is_followed
    }
    return render_template('news/other.html',data=data)


@pro_blu.route('/other_news_list')
def other_news_list():
    other_id = request.args.get('other_id')
    page = request.args.get('page',1)

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

    if not other:
        return jsonify(errno=RET.NODATA, errmsg='没有该用户数据')

    news_list = []
    total_pages = 1
    try:
        paginate = other.news_list.paginate(page,OTHER_NEWS_PAGE_MAX_COUNT)
        news_list = paginate.items
        total_pages = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询失败')

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    data = {
        "news_dict_li":news_dict_li,
        "page":page,
        "total_pages":total_pages
    }

    return jsonify(errno=RET.OK,errmsg='ok',data=data)